﻿using Canteen.Core.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Canteen.Core.Services
{
    public class ProductServiceImplement : IProductService
    {
        private readonly CanteenDbContext dbContext;
        public ProductServiceImplement(CanteenDbContext dbContext)
        {
            this.dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        }

        public async Task<Product> CreateProduct(Product product)
        {
            await dbContext.Products.AddAsync(product);
            if (await dbContext.SaveChangesAsync() > 0) return product;
            throw new Exception("保存商品信息失败");
        }
        public async Task<Product> UpdateProduct(Product product)
        {
            //先查询出来，因为操作被追踪的数据
            var entiy = await dbContext.Products.SingleOrDefaultAsync(s => s.Id == product.Id && s.StoreId == product.StoreId);
            //修改Name属性，被追踪的league状态属性就会变为Modify
            entiy.Name = product.Name;
            entiy.Type = product.Type;
            entiy.Price = product.Price;
            entiy.Number = product.Number;
            entiy.VitaminA = product.VitaminA;
            entiy.VitaminB = product.VitaminB;
            entiy.VitaminC = product.VitaminC;
            entiy.UpdateTime = DateTime.Now;
            //执行数据库操作
            if (await dbContext.SaveChangesAsync() > 0) return entiy;
            throw new Exception("修改商品信息失败");
        }

        public async Task<bool> DeleteProduct(int id)
        {
            var product = await dbContext.Products.SingleOrDefaultAsync(l => l.Id == id);
            dbContext.Products.Remove(product);//删除单个Leagues
            return await dbContext.SaveChangesAsync() > 0;
        }
        public async Task<Product> SelectProductById(int id)
        {
            return await dbContext.Products.SingleOrDefaultAsync(l => l.Id.Equals(id));
        }
        public async Task<Product> SelectProductByCode(string code)
        {
            return await dbContext.Products.SingleOrDefaultAsync(l => l.Code.Equals(code));
        }
        public async Task<PageList<Product>> GetPageList(ProductPageParameters parameters,int storeId)
        {
            var query = dbContext.Products.AsQueryable();
            if (storeId > 0)
            {
                query = query.Where(m => m.StoreId==storeId);
            }
            if (!string.IsNullOrWhiteSpace(parameters.Name))
            {
                query = query.Where(m => m.Name.Contains(parameters.Name.Trim()));
            }
            if (parameters.Type != null  && parameters.Type>0)
            {
                query = query.Where(m => m.Type.Equals(parameters.Type));
            }
            return await PageList<Product>.CreateAsync(query.OrderByDescending(o => o.CreateTime),
                parameters.Current,
                parameters.PageSize);
        }       
    }
}
